<script setup lang="ts">
import { ElMessage } from 'element-plus'
import detail from '../statistics/detail.vue'
import type { UseForm } from './page'
import edit from './edit.vue'
import { OperateType } from './operate.common'
import { useAssetModelClassifys, useAssetModels } from '@/utils/dataHook'
import { QueryObj } from '@/utils/dataHook/data'
import { usePage } from '@/utils/commonHook'
import assetsApi from '@/api/modules/assets'
import type { orderForm, orderInfo } from '@/api/modules/types/assets'
import { ModelType } from '@/types/common'
import type { doLoading } from '@/types/page'

const searchData = reactive(new QueryObj({
  objType: 'DIM.FilterCollection',
  Filters: [
    {
      Type: 'DIM.Assets.Filters.AssetChangeTimeFilter',
      FilterKey: 'Use',
      valueKey: 'UseTime',
    },
    {
      Type: 'DIM.Assets.Filters.AssetStateFilter',
      FilterKey: '',
      valueKey: 'DIM.Assets.Filters.AssetStateFilter',
      mutlip: true,
    },
    {
      Type: 'DIM.Assets.Filters.AssetModelFilter',
      FilterKey: '',
      valueKey: 'DIM.Assets.Filters.AssetModelFilter',
      mutlip: true,
    },
    {
      Type: 'DIM.Assets.Filters.AssetCodeFilter',
      FilterKey: '',
      valueKey: 'DIM.Assets.Filters.AssetCodeFilter',
      mutlip: true,
    },
    {
      Type: 'DIM.Assets.Filters.AssetModelClassifyFilter',
      FilterKey: '',
      valueKey: 'DIM.Assets.Filters.AssetModelClassifyFilter',
      mutlip: true,
    },
    {
      Type: 'DIM.GYHR.AssetFilters.OrderFormIDFilter',
      FilterKey: 'OFID',
      valueKey: 'OFID',
    },
    {
      Type: 'DIM.Assets.Filters.AssetChangeAccountFilter',
      FilterKey: 'Use',
      valueKey: 'UseAccount',
      mutlip: true,
    },
  ],
}))
const { page, pageNumChange, pageSizeChange } = usePage(getTableData)

const ModelClassifys = useAssetModelClassifys()
const AssetModels = useAssetModels()
const stateTypes = [
  {
    Name: '入库', StateID: 10,
  },
  {
    Name: '领用', StateID: 20,
  },
]

const editRef = ref()

function search() {
  page.PageNum = 1
  getTableData()
}
const tableData = ref<orderForm[]>([])
const loading = ref(false)

async function getTableData() {
  loading.value = true
  const res = await assetsApi.GetAssets({
    objFilter: searchData.getQuery(),
    objType: searchData.objType,
    pageSize: page.PageSize,
    pageNum: page.PageNum,
  })
  loading.value = false
  // console.log('%c [ res ]-27', 'font-size:13px; background:pink; color:#bf2c9f;', res)
  const { Rows, RecordsetCount } = res
  tableData.value = Rows || []
  page.RecordsetCount = RecordsetCount
}

const detailRef = ref()
function toDetail(row: orderInfo) {
  detailRef.value.open({ type: ModelType.edit, data: row })
}
const tableRef = ref()
function toBatch() {
  const rows = tableRef.value.getCheckboxRecords()
  if (!rows.length) {
    return ElMessage.warning('请选择要领用的资产')
  }
  const assetObjIDs = rows.map((item: orderInfo) => item.AssetObjID)
  editRef.value.open({ type: OperateType.batch, data: { ...rows[0], assetObjIDs } })
}
function toEdit(row: orderInfo) {
  editRef.value.open({ type: OperateType.single, data: row })
}

getTableData()

async function submitUse(formData: UseForm, doLoading: doLoading) {
  try {
    doLoading(true)
    await assetsApi.ChangeUse(formData)
    getTableData()
    editRef.value.close()
    ElMessage.success({
      message: '领用成功',
      type: 'success',
    })
  }
  catch (e) {
    doLoading(false)
  }
}

// async function toDel(row: ContractRow) {
//   await ElMessageBox.confirm(`确定删除合同 ${row.ContractCode} 吗？`, '提示', {
//     type: 'warning',
//   })
//   await contractApi.ContractsDelete({ contractObjID: row.ObjID })
//   ElMessage.success({
//     message: '删除成功',
//     type: 'success',
//   })
//   getTableData()
// }
</script>

<template>
  <div>
    <PageHeader>
      <template #content>
        <ElForm label-width="100">
          <ElRow>
            <ElCol :span="6">
              <ElFormItem label="订单号">
                <ElInput v-model="searchData.OFID" placeholder="订单号" clearable />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="领用日期">
                <ElDatePicker v-model="searchData.UseTime" value-format="YYYYMMDD" type="daterange" />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="资产状态">
                <ElSelect v-model="searchData['DIM.Assets.Filters.AssetStateFilter']" class="w-full" clearable>
                  <ElOption v-for="item in stateTypes" :key="item.StateID" :label="item.Name" :value="item.StateID" />
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="型号">
                <ElSelect v-model="searchData['DIM.Assets.Filters.AssetModelFilter']" class="w-full" clearable>
                  <ElOption v-for="item in AssetModels" :key="item.ObjID" :label="item.Name" :value="item.ObjID" />
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="设备编码">
                <ElInput v-model="searchData['DIM.Assets.Filters.AssetCodeFilter']" clearable />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="产品名称">
                <ElSelect v-model="searchData['DIM.Assets.Filters.AssetModelClassifyFilter']" class="w-full" clearable>
                  <ElOption v-for="item in ModelClassifys" :key="item.ObjID" :label="item.Name" :value="item.ObjID" />
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="领用人">
                <ElInput v-model="searchData.UseAccount" clearable />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6" class="flex flex-justify-end">
              <ElButton type="primary" @click="search">
                查询
              </ElButton>
              <ElButton type="success" @click="toBatch">
                批量领用
              </ElButton>
              <ElButton type="warning">
                导出
              </ElButton>
            </ElCol>
          </ElRow>
        </ElForm>
      </template>
    </PageHeader>
    <PageMain>
      <div v-auto-height="85">
        <vxe-table
          ref="tableRef"
          auto-resize border
          height="100%"
          :data="tableData"
          :loading="loading"
          :row-config="{ isCurrent: true }"
          :checkbox-config="{ checkMethod: ({ row }) => row.StateName === '入库' }"
        >
          <VxeColumn type="checkbox" width="80" />
          <VxeColumn type="seq" title="序号" width="80" />
          <VxeColumn field="OrderFormCode" title="订单号" min-width="150" />
          <VxeColumn field="AssetModelClassifyName" title="产品名称" min-width="150" />
          <VxeColumn field="AssetModelName" title="型号" width="150" />
          <VxeColumn field="OrderFormCode" title="设备编码" width="150">
            <template #default="{ row }">
              <el-button type="primary" link @click="toDetail(row)">
                {{ row.AssetCode }}
              </el-button>
            </template>
          </VxeColumn>
          <VxeColumn field="UseTime" title="领用日期" width="150" />
          <VxeColumn field="StateName" title="资产状态" width="140" />
          <VxeColumn field="UseAccount" title="领用人" min-width="120" />
          <VxeColumn field="operate" fixed="right" title="操作" width="160">
            <template #default="{ row }">
              <ElButton v-if="row.StateName === '入库'" type="success" link @click="toEdit(row)">
                领用
              </ElButton>
            </template>
          </VxeColumn>
        </vxe-table>
      </div>
      <ElPagination
        class="mt-4"
        :page-size="page.PageSize"
        :total="page.RecordsetCount"
        :current-page="page.PageNum"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[20, 50, 100]"
        @current-change="pageNumChange"
        @size-change="pageSizeChange"
      />
    </PageMain>
    <detail ref="detailRef" />
    <edit ref="editRef" @submit="submitUse" />
  </div>
</template>
